import Ajax from "/ajax" //ajax

/* 获取经纬度 */
let getLocation = app => {
	return new Promise((resolve, reject)=>{
		if(app.globalData.location){
			resolve(app.globalData.location)
		}else{
			wx.getLocation({
				type: 'wgs84',
				complete(res) {
					res.latitude?resolve({latitude:res.latitude,longitude:res.longitude}):reject(res.errMsg)
				}
			})
		}
	})
}

/* 登陆 */
let getOpenid = app => {
	return new Promise((resolve, reject)=>{
		wx.login({
			success: res => {
				if (res.code) {
					//发送res.code到后台换取 openId, sessionKey, unionId
					new Ajax().post("car_passenger/user_code",{code:res.code}).then(info=>{
						resolve(info)
					},err=>{
						reject(err)
					})
				} else {
					console.log('登录失败！' + res.errMsg)
					reject(res.errMsg)
				}
			}
		})
	})
}

/* 获取用户信息 */
const getSetAndUserInfo = app => {
	return new Promise((resolve, reject)=>{
		wx.getSetting({
		  success: res => {
			if (res.authSetting['scope.userInfo']) {
				// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
				wx.getUserInfo({
					success: res => {
						// 可以将 res 发送给后台解码出 unionId
						resolve(res.userInfo)
					}
				})
			}
		  }
		})
	})
}

module.exports = {
	getLocation,
	getSetAndUserInfo,
	getOpenid
}